/**
 * Copyright (c) e-test Co.Ltd. All right reserved.
 */
package com.link4a.doms.web.auth;

import com.link4a.doms.exception.IllegalPrivilegeException;
import com.link4a.doms.web.SessionContext;
import com.link4a.doms.web.UserWrapper;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 权限检查切面
 * @author zhao.zhihong
 * @date 2015年5月5日 下午5:48:13
 */
@Component
@Aspect
public class PrivilegeInterceptor {
	
	@Autowired
	private SessionContext sessionContext;

	@Pointcut("@annotation(com.link4a.doms.web.auth.Privilege)")
	private void process(){}
	
	@Before("com.link4a.doms.web.auth.PrivilegeInterceptor.process()")
	private void check(JoinPoint joinPoint) throws Throwable {
		MethodSignature signature = (MethodSignature)joinPoint.getSignature();
		Method method = signature.getMethod();
		Privilege auth = method.getAnnotation(Privilege.class);
		
		String[] requiredPermissions = auth.value();
		
		UserWrapper user = sessionContext.getUserWrapper();
		
		if (requiredPermissions != null && requiredPermissions.length > 0) {
			boolean hasPrivilege = false;
			
			//如果登录用户不具备任一权限，则抛出非法权限异常
			for (String permission : requiredPermissions) {
				if (user.getPermissions().contains(permission)) {
					hasPrivilege = true;
					break;
				}
			}
			
			if (!hasPrivilege) {
				throw new IllegalPrivilegeException();
			}
		}
	}
}
